<?php
#error_log(' '..' ', 3, MY_LOG_FILE);
class PWP_RegisterAction {

	private $mdt;
	private $view;
	private static $key_length = 5;

	public function __construct() {
		add_action('admin_init', array($this->getView(), 'registerResources'));
		add_action('wp_ajax_registerSite', array($this, 'registerSite'));
	}
	
	public static function init() {
		PWP_Mdt::createTable();
	}
	
	public static function destroy() {
		PWP_Mdt::dropTable();
	}
	
	public function registerSite() {
		$referer = explode('/', $_SERVER['HTTP_REFERER']);
		$referer = substr($referer[3].'/'.$referer[4], 0, 20);
		if ($referer != 'wp-admin/plugins.php') {
			$this->getView()->sendResponseJson(array('data'=>'true'));
			return;
		}
		if (!isset($_POST['key'])) {
			if ($this->getMdt()->siteKeyExist()) {
				$this->getView()->sendResponseJson(array('data'=>'true'));
			} else {
				$this->getView()->sendResponseJson(array('data'=>'false'));
			}
		} else {
			$userKey = $_POST['key']; // TODO escaping
			
			if (strlen($userKey) == self::$key_length) {
				$this->getMdt()->saveSiteKey($userKey);
				$this->getView()->sendResponseJson(array('data'=>'success'));
				return;
			}
			$this->getView()->sendResponseJson(array('data'=>'failure'));
		}
	}
	
	private function getMdt() {
		if ($mdt == null) {
			$mdt = new PWP_Mdt();
		}
		return $mdt;
	}
	
	private function getView() {
		if ($view == null) {
			$view = new PWP_View();
		}
		return $view;
	}
}
?>
